package com.gxpt.app.view;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.RadioButton;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.google.gson.Gson;
import com.gxpt.app.AppUtils;
import com.gxpt.app.BaseActivity;
import com.gxpt.app.Constant;
import com.gxpt.app.MessageEvent;
import com.gxpt.app.R;
import com.gxpt.app.bean.alipay_bean;
import com.gxpt.app.bean.wechatpay_bean;
import com.gxpt.app.bean.wechatquery_bean;
import com.gxpt.app.codes.alipay.AuthResult;
import com.gxpt.app.codes.alipay.PayResult;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.utils.T;
import com.utils.logger.Logger;
import com.utils.okhttputils.HttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.Map;

import okhttp3.Call;


/**
 * Created by dufeng on 2017/8/4.
 *
 * 微信接入
 * https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&id=1417751808&token=747dcf79fe2d2241bee962e6b6d339d5659747b0&lang=zh_CN
 */

@ContentView(R.layout.activity_pay_shopping)
public class Activity_pay_shopping extends BaseActivity {

    @ViewInject(R.id.toback)
    Button toback;

    @ViewInject(R.id.txt_title)
    TextView txt_title;

    @ViewInject(R.id.toPay)
    Button toPay;

    @ViewInject(R.id.txt_no)
    TextView txt_no;


    @ViewInject(R.id.txt_price)
    TextView txt_price;

//
//
    @ViewInject(R.id.r_zhifubao)
    RadioButton r_zhifubao;
//
    @ViewInject(R.id.r_weixin)
    RadioButton r_weixin;

    int pay_type = 0 ;

    String order_id;
    String total_price;

    int  type = 0;//0=> 商城 1=>服务;

    ///
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

		EventBus.getDefault().register(this);
        x.view().inject(this);
        IWXAPI msgApi = WXAPIFactory.createWXAPI(context, null);
        boolean isok = msgApi.registerApp(Constant.APP_ID);


        Bundle b = getIntent().getBundleExtra("DATA");
        if(b != null){
            order_id    = b.getString("order_id");
            total_price = b.getString("total_price");
            type        = b.getInt("PAY_TYPE");
        }

        initView();
    }

    	@Override
	protected void onDestroy() {
		EventBus.getDefault().unregister(this);
		super.onDestroy();
	}

	@Subscribe(threadMode = ThreadMode.MAIN)
	public void onMoonEvent(MessageEvent messageEvent){
		if(messageEvent.getMessageType()==Constant.ACTION_order_info){
            toNet_wechatquery();
		}
	}

    @Override
    public void initView() {
        txt_title.setText(getString(R.string.txt_zhifufangshi));

        txt_no.setText(""+order_id);
        txt_price.setText(getResources().getString(R.string.f_1)+total_price);

        r_zhifubao.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked){
                    pay_type = 1;
                    r_weixin.setChecked(false);
                }

            }
        });

        r_weixin.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked){
                    pay_type = 2;
                    r_zhifubao.setChecked(false);
                }

            }
        });
    }




    @Override
    public void initData() {

    }

    @Event(value={R.id.toback,R.id.toPay})
    private void getEvent(View view){
        switch(view.getId()){

            case R.id.toback:
                Dialog_detail();
                break;
            case R.id.toPay:
                if(pay_type == 0){
                    T.show(context,""+getResources().getString(R.string.alert_xuanzezhifufangshi_txt),1);
                }else if(pay_type == 1){
                    toNet_alipay();
                }else{
                    toNet_wechatpay();
                }

                break;

        }
    }

    /**
     * 监听Back键按下事件,方法2:
     * 注意:
     * 返回值表示:是否能完全处理该事件
     * 在此处返回false,所以会继续传播该事件.
     * 在具体项目中此处的返回值视情况而定.
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            Dialog_detail();
            return true;
        }else {
            return super.onKeyDown(keyCode, event);
        }

    }

    ///////////////////////////////////////////////支付宝
    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_AUTH_FLAG = 2;

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();

//                    Logger.i("resultInfo = "+resultInfo);
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
//                        T.show(context, "支付成功", 1);
                        EventBus.getDefault().post(new MessageEvent(Constant.ACTION_pay_success));
                        Intent goSuccess = new Intent();
                        goSuccess.setClass(context,Activity_pay_success.class);
                        startActivity(goSuccess);
                        finish();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        T.show(context, "支付失败", 1);
                    }
                    break;
                }
                case SDK_AUTH_FLAG: {
                    @SuppressWarnings("unchecked")
                    AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
                    String resultStatus = authResult.getResultStatus();

                    // 判断resultStatus 为“9000”且result_code
                    // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
                    if (TextUtils.equals(resultStatus, "9000") && TextUtils.equals(authResult.getResultCode(), "200")) {
                        // 获取alipay_open_id，调支付时作为参数extern_token 的value
                        // 传入，则支付账户为该授权账户
                        T.show(context,
                                "授权成功\n" + String.format("authCode:%s", authResult.getAuthCode()), 1);
                    } else {
                        // 其他状态值则为授权失败
                        T.show(context,
                                "授权失败" + String.format("authCode:%s", authResult.getAuthCode()), 1);

                    }
                    break;
                }
                default:
                    break;
            }
        }
    };







    //////NET DO
    StringCallback do_alipay = new StringCallback(){


        @Override
        public void onError(Call call, Exception e, int i) {
            Logger.e(e.getMessage());
        }

        @Override
        public void onResponse(String s, int i) {
            if(hud.isShowing()){
                hud.dismiss();
            }
            Logger.e(s);
            try{
                alipay_bean data = new Gson().fromJson(s, alipay_bean.class);
                if(data.state !=1 ){
                    T.show(context,data.msg,0);
                }else{
                    Logger.i(data.data);
                    alipay_do(data.data);
                }
            }catch (Exception e){
                e.printStackTrace();
                T.show(context,getResources().getString(R.string.alert_again),0);
            }
        }
    };


    private void alipay_do(final String orderInfo){
//        PayTask alipay = new PayTask(Activity_pay_shopping.this);
//        Map<String, String> result = alipay.payV2(orderInfo, true);
//        Logger.i("msp", result.toString());
//
//        Message msg = new Message();
//        msg.what = SDK_PAY_FLAG;
//        msg.obj = result;
//        mHandler.sendMessage(msg);


        Logger.i("orderInfo = "+orderInfo);
        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(Activity_pay_shopping.this);
                Map<String, String> result = alipay.payV2(orderInfo, true);
//                Logger.i("msp = "+ result.toString());

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    /////NET
    private void toNet_alipay(){
        hud.show();
        JSONObject jsonBody=new JSONObject();
        try {
            jsonBody.put("device_number",         AppUtils.get_device_id(context));
            jsonBody.put("device_type",           Constant.device_type);
            jsonBody.put("token",                 AppUtils.get_token(context));
            jsonBody.put("pageName",             "pay");
            jsonBody.put("serviceName",          "alipay");

            jsonBody.put("member_id",             AppUtils.get_user_id(context));
            jsonBody.put("order_id",              order_id);
            jsonBody.put("type",                  type);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        HttpUtils.http_post_string(Constant.URL_alipay,jsonBody.toString(),do_alipay);
    }

    private void toNet_wechatpay(){
        hud.show();
        JSONObject jsonBody=new JSONObject();
        try {
            jsonBody.put("device_number",         AppUtils.get_device_id(context));
            jsonBody.put("device_type",           Constant.device_type);
            jsonBody.put("token",                 AppUtils.get_token(context));
            jsonBody.put("pageName",             "pay");
            jsonBody.put("serviceName",          "wechatpay");

            jsonBody.put("member_id",             AppUtils.get_user_id(context));
            jsonBody.put("order_id",              order_id);
            jsonBody.put("type",                  type);
        } catch (JSONException e) {
            e.printStackTrace();
        }
//        Logger.i(""+jsonBody.toString()+"["+Constant.URL_wechatpay+"]");
        HttpUtils.http_post_string(Constant.URL_wechatpay,jsonBody.toString(),do_wechatpay);
    }

    StringCallback do_wechatpay = new StringCallback(){


        @Override
        public void onError(Call call, Exception e, int i) {
            Logger.e(e.getMessage());
        }

        @Override
        public void onResponse(String s, int i) {
            if(hud.isShowing()){
                hud.dismiss();
            }
//            Logger.e("WX Pay = "+s);
            try{
                wechatpay_bean data = new Gson().fromJson(s, wechatpay_bean.class);
                if(data.state !=1 ){
                    T.show(context,data.msg,0);
                }else{

                    if(data.data.result_code==null && data.data.err_code_des==null){//去支付



                        PayReq request = new PayReq();
                        request.appId			= data.data.appid;
                        request.partnerId		= data.data.partnerid;
                        request.prepayId		= data.data.prepayid;
                        request.nonceStr		= data.data.noncestr;
                        request.timeStamp		= data.data.timestamp;
                        request.packageValue   	= Constant.APP_package;
                        request.sign			= data.data.paySign;

                        IWXAPI api= WXAPIFactory.createWXAPI(Activity_pay_shopping.this,Constant.APP_ID);
                        api.sendReq(request);
//                           Logger.d("send return :"+api.sendReq(request));


                    }else{//已经支付
                        T.show(context,data.data.err_code_des,0);
                    }


                }
            }catch (Exception e){
                e.printStackTrace();
                T.show(context,getResources().getString(R.string.alert_again),0);
            }
        }
    };

    private void toNet_wechatquery(){
        hud.show();
        JSONObject jsonBody=new JSONObject();
        try {
            jsonBody.put("device_number",         AppUtils.get_device_id(context));
            jsonBody.put("device_type",           Constant.device_type);
            jsonBody.put("token",                 AppUtils.get_token(context));
            jsonBody.put("pageName",             "pay");
            jsonBody.put("serviceName",          "wechatquery");

            jsonBody.put("member_id",             AppUtils.get_user_id(context));
            jsonBody.put("order_id",              order_id);
            jsonBody.put("type",                  type);
        } catch (JSONException e) {
            e.printStackTrace();
        }
//        Logger.i(""+jsonBody.toString()+"["+Constant.URL_wechatpay+"]");
        HttpUtils.http_post_string(Constant.URL_wechatquery,jsonBody.toString(),do_wechatquery);
    }

    StringCallback do_wechatquery = new StringCallback(){


        @Override
        public void onError(Call call, Exception e, int i) {
            Logger.e(e.getMessage());
        }

        @Override
        public void onResponse(String s, int i) {
            if(hud.isShowing()){
                hud.dismiss();
            }
            Logger.e("WX Pay = "+s);
            try{
                wechatquery_bean data = new Gson().fromJson(s, wechatquery_bean.class);
                if(data.state !=1 ){
                    T.show(context,data.msg,0);
                }else{
                    String msg = AppUtils.getWXPay_STUTS_NAME(data.data);
                    T.show(context,msg,1);

                    if(AppUtils.getWXPay_STUTS(data.data)){
                        EventBus.getDefault().post(new MessageEvent(Constant.ACTION_pay_success));
                        Intent goSuccess = new Intent();
                        goSuccess.setClass(context,Activity_pay_success.class);
                        startActivity(goSuccess);
                        finish();
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
                T.show(context,getResources().getString(R.string.alert_again),0);
            }
        }
    };


    public void Dialog_detail(){
        final Dialog dialog=new Dialog(context,R.style.customDialogStyle);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        View view= LayoutInflater.from(context).inflate(R.layout.dialog_pay_exit, null);
        dialog.setContentView(view);

        Button toExit = (Button)view.findViewById(R.id.toExit);
        Button toSure = (Button)view.findViewById(R.id.toSure);
        toExit.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View v) {
                closeActivity();
            }
        });

        toSure.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        Window dialogWindow = dialog.getWindow();
        dialogWindow.setWindowAnimations(R.style.commonAnimDialogStyle);
        dialogWindow.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
        dialogWindow.setGravity(Gravity.BOTTOM);
        dialog.show();

    }
}
